<template>
	<!-- 背景音乐列表 -->
	<view>
		<view class="list">
			<z-paging ref="paging" v-model="list" @query="queryList" :fixed="false" :auto-clean-list-when-reload="false"
				:auto="true" :paging-style="{ height:'100%' }" :show-refresher-when-reload="true"
				:default-page-size="10" :hide-empty-view="true">
				<view class="box1">
					<view class="box_item1" @click="change(item.mateId)" :class="item.mateId===musicMateId?'act':''"
						v-for="(item,index) in list" :key="item.mateId">
						<view class="zl-flex zl-row-between">
							<view class="zl-flex">
								<image src="/static/clone/voiceIcon.png" mode="" class="play"
									style="width: 80rpx;height: 80rpx;">
								</image>
								<view class="zl-flex-col zl-m-l-18">
									<view class="zl-font-30 zl-color-000 zl-one-yichu" style="width: 360rpx;">
										{{item.name}} </view>
									<view class="zl-font-20 zl-color-999 zl-m-t-8" style="opacity: 0.6;">
										{{$util.fomateDate(item.createTime*0.001)}}
									</view>
								</view>
								<image v-show="item.mateId===musicMateId"
									style="position: absolute;bottom: -2rpx;right: -2rpx;width: 50rpx;"
									src="/static/clone/choosed.png" mode="widthFix"></image>
							</view>
							<view class="zl-flex">
								<view class="download" v-if="playIng&&item.mateId==PlaymusicMateId"
									@click.stop="stop()">
									<image src="/static/work/stop.png" mode=""
										style="width: 25rpx;height: 25rpx;margin-right: 6rpx;"></image> 暂停
								</view>
								<view v-else class="download" @click.stop="listen(item)">
									<image src="/static/work/listen.png" mode=""
										style="width: 25rpx;height: 25rpx;margin-right: 6rpx;"></image> 试听
								</view>
								<!-- <view class="edit">
									编辑
								</view> -->
							</view>
						</view>
					</view>
					<view v-if="list.length<=0" class=" zl-flex-col zl-col-center"
						style="width: 690rpx;margin-top: 50%;">
						<image src="/static/work/empty.png" mode="widthFix" style="width: 230rpx;margin-bottom: 48rpx;">
						</image>
						<text class="zl-font-30 zl-color-666">空空如也，您还没有创建哦~</text>
					</view>
				</view>
			</z-paging>
		</view>
		<view class="add-box zl-flex zl-row-center" @click="upAudio()">
			<image src="/static/icon/add-black.png" mode=""></image>
			上传背景音乐
		</view>
		<view class="footer zl-flex zl-row-center">
			<view @click="change_only()" class="only zl-flex">
				<image v-if="musicMateId===0" src="/static/icon/selected.png"></image>
				<image v-else src="/static/icon/select.png"></image>
				<text class="zl-font-30 zl-color-black zl-m-l-20">随机背景音乐</text>
			</view>
			<view class="btn" @click="sure()"> 确定 </view>
		</view>
		<uni-popup :animation="false" ref="popup" type="center" background-color="#fff"
			border-radius="20rpx 20rpx 20rpx 20rpx">
			<view class=""
				style="width: 560rpx;height: auto;background-color: #fff;border-radius: 20rpx;padding:40rpx 30rpx;">
				<view class="" style="display: flex;justify-content: flex-end;width: 100%;">
					<image @click="close()" style="width: 34rpx;height: 34rpx;" src="/static/icon/pop_close.png"
						mode=""></image>
				</view>
				<view class="pro_title">上传进度</view>
				<view class="pros zl-m-t-20">
					<progress :percent="pro" show-info stroke-width="3" />
				</view>
				<view class="pros zl-m-t-20">
					<progress :percent="getPro()" show-info stroke-width="3" />
				</view>
				<view class="pro_des zl-m-t-20">正在上传 {{cur_count}}/{{pro_count}}</view>
			</view>
		</uni-popup>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				list: [],
				musicMateId: 0,
				playurl: '',
				playIng: false,
				innerAudioContext: null,
				PlaymusicMateId: 0,
				file: {},
				pro: 0,
				pro_count: 0,
				cur_count: 0,
			};
		},
		onLoad(opt) {
			if (opt.musicMateId) {
				this.musicMateId = parseInt(opt.musicMateId)
			}
		},
		onUnload() {
			this.stop()
		},
		methods: {
			change(id) {
				this.musicMateId = id;
			},
			queryList(page, limit) {
				this.api.mate.getmatelist({
					page: page,
					limit: limit,
					mateType: 2,
					mateClass: 2
				}).then(res => {
					if (res.code === 0) {
						this.$refs.paging.complete(res.data.list)
					} else {
						this.$refs.paging.complete(false);
						this.$util.msg(res.msg);
					}
				}).catch(err => {
					this.$refs.paging.complete(false);
					this.$util.msg('请检查网络连接！');
				})
			},
			sure() {

				uni.$emit('choosemusicId', this.musicMateId);
				uni.navigateBack()
			},
			listen(item) {
				this.api.mate.geturl({
					mateId: item.mateId
				}).then(res => {
					if (res.code === 0) {
						this.PlaymusicMateId = item.mateId
						this.playurl = res.data.url;
						this.playIng = true;
						this.play();
					} else {
						this.$util.msg(res.msg);
					}
				}).catch(err => {
					this.$util.msg('请检查网络连接！');
				})
			},
			play() {
				if (this.innerAudioContext) {
					this.innerAudioContext.stop();
				}
				this.innerAudioContext = uni.createInnerAudioContext();
				this.innerAudioContext.src = this.playurl;
				this.innerAudioContext.play();
				this.innerAudioContext.onEnded(() => {
					this.playIng = false;
				});
			},
			// 暂停
			stop() {
				if (this.innerAudioContext) {
					this.innerAudioContext.stop();
				}
				this.playurl = '';
				this.playIng = false;
			},
			change_only() {
				this.musicMateId = 0
			},
			upAudio() {
				wx.chooseMessageFile({
					count: 2, //默认100
					type: 'file',
					extension: ['mp3', 'MP3', 'aac', 'm4a', 'wav'],
					sourceType: ['album', 'camera'],
					success: res => {
						console.log(res);
						const tempFilePath = res.tempFiles[0].path;
						this.file.tempFilePath = tempFilePath;
						this.file.size = res.size;
						this.uploadAll(res.tempFiles)
					},
					fail: err => {
						console.log(err);
					}
				});
			},
			getPro() {
				return Math.floor((this.pro_count <= 0 ? 0 : (this.cur_count / this.pro_count * 100)) * 100) / 100;
			},
			close() {
				this.$refs.popup.close();
			},
			async uploadAll(list) {
				for (let i = 0; i < list.length; i++) {
					this.cur_count = i + 1;
					var item = list[i];
					console.log(item);
					var suffix = item.path.substr(item.path.lastIndexOf("."));
					var fileName = new Date().getTime() + '_' + this.$util.randomString(8) + suffix;
					let gs = ''
					let Index = item.path.lastIndexOf(".");
					gs = item.path.substr(Index + 1).toLowerCase();
					if (gs !== "mp3" && gs !== "m4a" && gs !== "wav") {
						this.$util.msg('第' + (i + 1) + '个素材格式不支持！');
						await new Promise((resolve, reject) => {
							setTimeout(() => {
								resolve({});
							}, 2300);
						});
						continue;
					}
					if (item.size > 1024 * 1024 * 20) {
						this.$util.msg(`第${i+1}个文件超出大小，请上传低于20兆的文件`)
						await new Promise((resolve, reject) => {
							setTimeout(() => {
								resolve({});
							}, 2300);
						});
						continue;
					}
					var signRes = undefined;
					try {
						signRes = await this.api.mate.applyuploadmusic({
							fileName: item.name,
						});
						if (signRes.code != 0) {
							// #ifdef MP-WEIXIN
							wx.reportEvent("media_upload", {
								code: signRes.code,
								msg: signRes.msg
							})
							// #endif
							this.$util.msg(signRes.msg);
							// uni.hideLoading()
							return;
						}
					} catch (e) {
						//TODO handle the exception
						// #ifdef MP-WEIXIN
						wx.reportEvent("media_upload", {
							exception: JSON.stringify(e)
						})
						// #endif
						this.$util.msg('上传初始化失败！');
						// uni.hideLoading()
						return;
					}
					if (!signRes || !signRes.data) {
						// #ifdef MP-WEIXIN
						wx.reportEvent("media_upload", {
							api_exception: '获取签名失败！'
						})
						// #endif
						this.$util.msg('上传初始化失败！');
						// uni.hideLoading()
						return;
					}
					var sign = signRes.data;
					this.pro_count = list.length;
					this.pro = 0;
					this.$refs.popup.open()
					try {
						var uploadRes = await this.upload(sign, item.path);
						console.log(uploadRes, '上传文件结果');
					} catch (e) {
						this.$util.msg('第' + (i + 1) + '个音频，' + e.message);
						this.pro = 0;
						await new Promise((resolve, reject) => {
							setTimeout(() => {
								resolve({});
							}, 2300);
						});
					}
					if (i < list.length - 1) {
						this.pro = 0;
						await new Promise((resolve, reject) => {
							setTimeout(() => {
								resolve({});
							}, 1000);
						});
					}
				}
				this.$refs.popup.close();
				this.$refs.paging.reload();
				setTimeout(() => {
					this.pro_count = 0;
					this.cur_count = 0;
					this.pro = 0;
				}, 1000);
			},
			async upload(sign, tempFilePath) {
				return await new Promise((resolve, reject) => {
					var task = uni.uploadFile({
						url: sign.host,
						filePath: tempFilePath,
						fileType: 'audio',
						name: 'file',
						formData: sign.formData,
						timeout: 3600000,
						success: (res) => {
							console.log(res);
							if (res.statusCode === 200) {
								try {
									let data = JSON.parse(res.data)
									if (data.code === 0) {
										resolve(data.data);
									} else {
										reject(new Error(data.msg))
									}
								} catch (e) {
									reject(new Error('解析上传结果失败！'))
								}
							} else {
								reject(new Error('上传失败！'));
							}
						},
						fail: (err) => {
							// #ifdef MP-WEIXIN
							wx.reportEvent("media_upload", {
								aliyun_exception: JSON.stringify(err),
							})
							// #endif
							reject(new Error('上传失败！'));
						}
					});
					task.onProgressUpdate((pro) => {
						this.pro = pro.progress;
						// console.log(this.pro);
					});
				});
			},
		}
	}
</script>
<style lang="scss" scoped>
	.add-box {
		margin-top: 30rpx;
		margin-left: 30rpx;
		width: 690rpx;
		height: 100rpx;
		border: 2rpx solid #333;
		border-radius: 10rpx;
		font-size: 30rpx;
		font-weight: 500;

		image {
			width: 30rpx;
			height: 30rpx;
			margin-right: 10rpx;
		}
	}

	.list {
		margin: 0 30rpx;
		width: 750rpx;
		height: calc(100vh - 190rpx - 100rpx - 30rpx - 30rpx);
		background-color: #EDF0F4;

		.box {
			display: flex;
			flex-direction: row;
			gap: 30rpx;
			flex-wrap: wrap;

			.box_item {
				width: 330rpx;

				.video {
					width: 100%;
					height: 486rpx;
				}

				.content {
					background-color: #fff;
					padding: 24rpx 30rpx;
					border-radius: 0rpx 0rpx 10rpx 10rpx;
				}
			}
		}

		.box1 {
			width: 690rpx;
			border-radius: 20rpx;

			.act {
				border: 5rpx solid #EB5E00 !important;
			}

			.box_item1 {
				padding: 40rpx 30rpx;
				// height: 160rpx;
				margin-top: 30rpx;
				display: flex;
				flex-direction: column;
				background: #FFFFFF;
				border-radius: 20rpx;
				border: 5rpx solid #fff;
				position: relative;

				.line {
					margin-top: 40rpx;
					width: 633rpx;
					height: 1rpx;
					border: 1rpx solid #979797;
					opacity: 0.2;
				}

				.content {
					margin-top: 30rpx;
					font-size: 24rpx;
					color: #999999;
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
				}
			}
		}

		.download {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 121rpx;
			height: 56rpx;
			background: #FFFFFF;
			border-radius: 10rpx;
			border: 2rpx solid #000000;
			font-weight: 400;
			font-size: 24rpx;
			color: #000000;
		}

		.edit {
			margin-left: 24rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 85rpx;
			height: 56rpx;
			background: #FFFFFF;
			border-radius: 10rpx;
			border: 1rpx solid #000000;
			font-weight: 400;
			font-size: 24rpx;
			color: #000000;
		}
	}

	.btn {
		background-color: #FFFFFF;
		margin-bottom: 30rpx;
		height: 120rpx;
		border-radius: 10rpx;
		color: #131415;
		font-weight: 500;
	}

	.footer {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 750rpx;
		height: 190rpx;
		background: #FFFFFF;

		.only {
			width: 330rpx;
			height: 88rpx;

			image {
				width: 30rpx;
				height: 30rpx;
			}
		}

		.btn {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 330rpx;
			height: 110rpx;
			background: linear-gradient(90deg, #EB7A00 0%, #EB5E00 100%);
			box-shadow: 0rpx 10rpx 20rpx 0rpx rgba(66, 106, 171, 0.29);
			border-radius: 20rpx;
			font-size: 36rpx;
			color: #F9F9F9;
		}
	}

	.pro_title {
		font-size: 32rpx;
		font-weight: bold;
		text-align: center;
	}

	.pro_des {
		font-size: 28rpx;
		font-weight: bold;
		text-align: center;
		color: darkblue;
	}

	.video_poo_title {
		width: 100%;
		text-align: center;
		font-size: 30rpx;
		font-weight: 500;
	}
</style>